# coding=utf-8
__author__ = 'liubin'

from sqlalchemy import Column, Integer, String, BigInteger, ForeignKey, Boolean
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy.ext.hybrid import hybrid_method
from sqlalchemy.sql.expression import text
from project.tools import JsonpickleMixin, Base, md5
from base import BaseModel

class User(BaseModel, Base):
    '''
    用户表
    '''
    __tablename__ = 'm_user'
    #id = Column('id', BigInteger, primary_key=True)
    userId = Column('user_id', String(50), nullable=False)
    name = Column('name', String(200), nullable=False)
    password = Column('password', String(50), nullable=False)
    isDeleted = Column('is_deleted', Boolean, server_default=text('FALSE'))
    roleId = Column('role_id', BigInteger, ForeignKey('m_role.id'), nullable=False)
    role = relationship("Role", backref="users", foreign_keys=[roleId])

    @declared_attr
    def insertUserObj(cls):
        backref = 'inserted' + cls.__name__ + 's'
        return relationship("User", backref=backref, primaryjoin ="foreign(User.id)==remote(User.insertUser)")

    @declared_attr
    def updateUserObj(cls):
        backref = 'updated' + cls.__name__ + 's'
        return relationship("User", backref=backref, primaryjoin ="foreign(User.id)==remote(User.updateUser)")


    def __init__(self, data=None):
        """
        初始化
        :return:
        """
        if data:
            self.userId = data.get('userId')
            self.name = data.get('name')
            self.password = data.get('password')
            self.isDeleted = False
            self.roleId = data.get('roleId')


    @hybrid_method
    def set_encrypt_pwd(self, pwd):
        self.password = md5(pwd)


    def __getstate__(self):
        '''
        重写model的__getstate__
        删掉password
        :return:
        '''
        state = JsonpickleMixin.__getstate__(self)
        del state['password']
        return state


class Role(BaseModel, Base):
    '''
    权限表
    '''
    __tablename__ = 'm_role'
    #id = Column('id', BigInteger, primary_key=True)
    code = Column('code', String(10), nullable=False)
    name = Column('name', String(200), nullable=False)
    isDeleted = Column('is_deleted', Boolean, server_default=text('FALSE'))

    def __init__(self, data=None):
        """
        初始化
        :return:
        """
        if data:
            self.code = data.get('code')
            self.name = data.get('name')
            self.isDeleted = False

    def __getstate__(self):
        """
        覆盖menu的处理
        :return:
        """
        state = JsonpickleMixin.__getstate__(self)
        # if 'menus' in state:
        #     menus = []
        #     for menu in state['menus']:
        #         menus.append(menu.__getstate__())
        #     state['menus'] = menus
        return state

class MenuRole(BaseModel, Base):
    '''
    菜单权限表
    '''
    __tablename__ = 'r_menu_role'
    roleId = Column('role_id', BigInteger, ForeignKey('m_role.id'), nullable=False)
    role = relationship("Role", backref="menus")
    menu = Column('menu', String(50), nullable=False)
    enabled = Column('is_enabled', Boolean, server_default=text('FALSE'))

    def __init__(self, data=None):
        """
        初始化
        :param data:
        :return:
        """
        if data:
            self.roleId = data.get('roleId')
            self.menu = data.get('menu')
            self.enabled = data.get('enabled')